#include "stdafx.h"
#include "Renderer.h"


Renderer::Renderer()
{
}


Renderer::~Renderer()
{
}

void Renderer::InitD3D(HWND hWnd, unsigned short windowWidth, unsigned short windowHeight)
{
	DXGI_SWAP_CHAIN_DESC swapDesc;
	ZeroMemory(&swapDesc, sizeof(swapDesc));

	swapDesc.BufferCount = 1;									//one back buffer
	swapDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;	//32 bit color
	swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;		//swap chain usage
	swapDesc.OutputWindow = hWnd;								//the window to be used
	swapDesc.SampleDesc.Count = 4;								//num of multisamples
	swapDesc.Windowed = TRUE;									//windowed or fullscreen

	//TODO: ADD SUPPORT FOR MULTIPLE FEATURE LEVELS
	D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, NULL, NULL, D3D11_SDK_VERSION,
		&swapDesc, &swapChain, &device, NULL, &context);

	//get address of backbuffer
	ID3D11Texture2D *pBackBuffer;
	swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

	//use buffer address to create render target
	device->CreateRenderTargetView(pBackBuffer, NULL, &backbuffer);
	pBackBuffer->Release();

	//set the render target as the back buffer
	context->OMSetRenderTargets(1, &backbuffer, NULL);

	//set the viewport
	D3D11_VIEWPORT viewport;
	ZeroMemory(&viewport, sizeof(viewport));

	viewport.TopLeftX = 0;
	viewport.TopLeftY = 0;
	viewport.Width = windowWidth;
	viewport.Height = windowHeight;

	context->RSSetViewports(1, &viewport);
}

void Renderer::RenderFrame(void)
{
	float clearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
	context->ClearRenderTargetView(backbuffer, clearColor);

	//do 3d rendering here

	//switch back and front buffer
	swapChain->Present(0, 0);
}

void Renderer::CleanD3D(void)
{
	//close and release all existing COM objects
	swapChain->Release();
	device->Release();
	context->Release();
	backbuffer->Release();
}